%::PROVIDES=(
	name	=> ["STARTED_APP"],
	desc	=> ["Handle STARTED_APP request actions"],
	type	=> "request",
	code	=> \&::do_handle_startedapp
);

#########################################################################
# The started_app also checks to see if the specified application	#
# has a live-lems session and starts it on this node. The pid 		#
# information is registered, as is the port to communicate to it on.	#
# The lems configuration file on the local node will need to be:	#
# /etc/cluster/application/lems.local.xml.				#
#########################################################################

sub ::do_handle_startedapp {
my $args=shift;
my ($app,$h,$flags,$rc);

	if(!exists($args->{APP})) {
		logwarn("STARTED_APP request missing APP argument");
		return "MISSING_ARG";
	}

	$h=hostname;
	$app=$args->{APP};
	if(!exists($appmap->{$app})) {
		logwarn("Specified application is not registered");
		return "NOT_REGISTERED";
	}

	$appmap->{$app}->{STATE}="STARTED";
	$appmap->{$app}->{NODE}=$h;
	$appmap->{$app}->{STARTTIME}=time;

	$h=hostname;
	queue_it("APP_UPDATE app=$app state=STARTED node=$h monitor=0 starttime=".time);

	#################################################################
	# We also attempt to check for a suitable lems file, and if	#
	# available start it as a child process.			#
	#################################################################

	if(-f "/etc/cluster/$app/lems.local.xml") {

		my $lemsport=get_allocated_resource(hostname,"PORT",$app,"%%LEMS",undef);
		if($lemsport==-1) {
			logwarn("Missing port entry in lems configuration file - lems not started!");
			return "OK";
		}

		$appmap->{$app}->{LEMSPORT}=$lemsport;

		#########################################################
		# Now we start the session with --detach to ensure it	#
		# runs as a background task.				#
		#########################################################

		$flags="";
		$flags="--verbose" if $ARG_verbose;
		$rc=forknwait("/opt/linuxha14/bin/lems.pl $flags --detach --application $app --config /etc/cluster/$app/lems.local.xml");
		if($rc) {
			logwarn("Unable to run lems session! - exec failed!");
			return "OK";
		}
		$appmap->{$app}->{MONITOR}=1;
		logmsg("Lems session for $app started");
		queue_it("APP_UPDATE app=$app state=STARTED node=$h monitor=1 starttime=".time);
	}
	return "OK";
}

1;
